<?php

/* 创建目录 */
function makedir($path, $root = '')
{
  $path = explode('/', trim($path, '/'));
  while ($dir = array_shift($path)) {
    $root .= '/' . $dir;
    if (!is_dir($root)) {
      mkdir($root);
    }
  }
}

function uploadImage($type, $dir = null, $thumbSizes = [], $filesField = 'file', $filesIndex = null)
{
  if (!isset($_FILES[$filesField]) || (is_null($filesIndex) && ($_FILES[$filesField]['error'] || !$_FILES[$filesField]['size'])) ||
      (!is_null($filesIndex) && ($_FILES[$filesField]['error'][$filesIndex] || !$_FILES[$filesField]['size'][$filesIndex]))) {
    return [ 'error' => '文件上传失败' ];
  }
  $contentType = strtolower(is_null($filesIndex) ? $_FILES[$filesField]['type'] : $_FILES[$filesField]['type'][$filesIndex]);
  if (!in_array($contentType, [ 'image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif' ])) {
    return [ 'error' => '文件格式无效' ];
  }
  $filename = randomString(6);
  if (!isset($dir)) {
    $dir = date('Ymd');
  }
  $filename = $dir . '/' . $filename;
  switch ($contentType) {
    case 'image/pjpeg':
    case 'image/jpeg':
    case 'image/jpg':
      $extname = '.jpg';
      break;
    case 'image/png':
      $extname = '.png';
      break;
    case 'image/gif':
      $extname = '.gif';
      break;
  }
  $source = is_null($filesIndex) ? $_FILES[$filesField]['tmp_name'] : $_FILES[$filesField]['tmp_name'][$filesIndex];
  $fileModel = Azalea\Model::getModel('file');
  $fileUrl = $fileModel->upload($type, $source, $filename . $extname, $contentType);
  if (!$fileUrl) {
    return [ 'error' => '文件上传失败' ];
  }
  // 生成缩略图
  $thumbDir = dirname(VARPATH) . '/images';
  makedir($thumbDir);
  $imageModel = Azalea\Model::getModel('image');
  $thumbFileIds = [];
  foreach ($thumbSizes as $id => $size) {
    $imageModel->process($source, [ 'width' => $size[0], 'height' => $size[1] ]);
    $thumbSource = $thumbDir . '/' . Azalea\Text::random(16);
    $imageModel->output($thumbSource);
    $thumbFileIds[$id] = $fileModel->upload($type, $thumbSource, $filename . '_' . $id . $extname, $contentType);
    unlink($thumbSource);
  }
  $size = is_null($filesIndex) ? $_FILES[$filesField]['size'] : $_FILES[$filesField]['size'][$filesIndex];
  return [ 'url' => $fileUrl, 'filename' => $filename . $extname, 'size' => $size, 'thumb' => $thumbFileIds ];
}


function fun_adm_each(&$array){
  $res = [];
  $key = key($array);
  if($key !== null){
    next($array);
    $res[1] = $res['value'] = $array[$key];
    $res[0] = $res['key'] = $key;
  } else {
    $res = false;
  }
  return $res;
}
function randomString($len, $type = null)
{
  return  Azalea\Text::random($len, $type);
}

function url($path, $includeDomain = false)
{
  static $domainUrl = null;
  if (!isset($domainUrl)) {
    $domainUrl = PROTOCOL . '://' . strtolower($_SERVER['HTTP_HOST']);
  }
  if (!strcasecmp(substr($path, 0, 7), 'http://') || !strcasecmp(substr($path, 0, 8), 'https://')) {
    return $path;
  }
  return ($includeDomain ? $domainUrl : '')  .  '/' . ltrim($path, '/');
}

function urlStatic($url)
{
  if (!strcasecmp(substr($url, 0, 7), 'http://') || !strcasecmp(substr($url, 0, 8), 'https://')) {
    return $url;
  }
  return url(Azalea\Config::get('static_url', 'static/' . Azalea\Config::get('theme', 'default') . '/' . ltrim($url, '/') ) );
}

function access($message = '', $filename = 'access')
{
  if (!is_string($message)) {
    $message = json_encode($message);
  }
  file_put_contents(VARPATH . '/' . $filename . '.log', date('Y-m-d h:i:sa') . ' - ' . $message . PHP_EOL, FILE_APPEND);
}

function debug($message = '')
{
  file_put_contents(VARPATH . '/debug.log', date('Y-m-d h:i:sa') . ' - ' . json_encode($message) . PHP_EOL, FILE_APPEND);
}

function timer()
{
  return Azalea\timer();
}

function getMessages($clear = true)
{
  if (!isset($_SESSION['bpf_msgs'])) {
    return [];
  }
  $messages = $_SESSION['bpf_msgs'];
  if ($clear) {
    unset($_SESSION['bpf_msgs']);
  }
  return $messages;
}

function setMessage($value, $type = 'info')
{
  if (!isset($_SESSION['bpf_msgs'])) {
    $_SESSION['bpf_msgs'] = [];
  }
  $_SESSION['bpf_msgs'][] = [
    'type' => $type,
    'value' => $value,
  ];
}

function hasEmpty($tagers = [])
{
  foreach ($tagers as $tager) {
    if (empty($tager)) {
      return true;
    }
  }
  return false;
}

function is_phone($phonenumber) {
  if (preg_match("/^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$/", $phonenumber)) {
    return true;
  }
  return false;
}

function is_url($url) {
  return (bool)filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) !== false;
}


function is_email($email)
{
  if (preg_match("/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/", $email)) {
    return true;
  }
  return false;
}

function is_iphone()
{
  $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  if(strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
    return true;
  }
  return false;
}


function replace_unicode_escape_sequence($match) {
  return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}
function unicode_decode($str) {
  return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $str);
}

function maskString($string, $type = null)
{
  if ($type == 'email') {
    $domain = mb_strrchr($string, '@');
    return maskString(mb_substr($string, 0, -mb_strlen($domain))) . $domain;
  } else {
    $len = mb_strlen($string, 'utf8');
    if ($len < 3) {
      return mb_substr($string, 0, 1) . '***';
    } else {
      $charLen = intval($len / 3);
      $maskLen = $len - $charLen - $charLen;
      return mb_substr($string, 0, $charLen) . str_repeat('*', $maskLen) . mb_substr($string, -$charLen);
    }
  }
  return $string;
}

function str_replace_limit($search, $replace, $string, $limit = 1) {
  $pos = strpos($string, $search);

  if ($pos === false) {
      return $string;
  }

  $searchLen = strlen($search);

  for ($i = 0; $i < $limit; $i++) {
      $string = substr_replace($string, $replace, $pos, $searchLen);

      $pos = strpos($string, $search);

      if ($pos === false) {
          break;
      }
  }
  return $string;
}